<?php
namespace app\plus\controller;

use app\common\model\FormFieldModel;
use app\common\model\FormModel;
use Org\Util\HelpUtil;
use think\Controller;
use think\Db;
use think\Request;
use think\Validate;

class FormController extends Controller
{

    private $formModel;
    private $formFieldModel;

    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->formModel      = new FormModel();
        $this->formFieldModel = new FormFieldModel();
    }

    /**
     * 添加表单内容
     */
    public function add()
    {
        $data = $this->request->post();
        if (!$this->request->has('form_id')) {
            $this->error('表单参数错误');
        }
        $formId    = $data['form_id'];
        $fieldList = $this->formFieldModel->where('form_id', $formId)->order('field_sort desc')->select();
        $rule      = [];
        foreach ($fieldList as $k => $v) {
            if ($this->request->has($v['field_name'])) {
                if (!empty($v['validate'])) {
                    $validate                                         = implode("|", $v['validate']);
                    $rule[$v["field_name"] . '|' . $v['field_title']] = $validate;
                }
            }
        }
        $validate = new Validate($rule);
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        } else {
            if ($this->request->has('vcode')) {
                if (!captcha_check($this->request->post('vcode'))) {
                    $this->error('验证码填写错误！');
                };
            }
            $data['user_ip']     = HelpUtil::getIp();
            $data['create_time'] = time();
            $data['update_time'] = time();
            $tableName           = $this->formModel->where('form_id', $data['form_id'])->value('table_name');
            unset($data['vcode']);
            Db::table('form_' . $tableName)->insert($data);
            $this->success('提交成功');
        }
    }
}